package dev.ece.suit.text;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

import dev.ece.util.lib.Vector4f;

public class RangeColor {

	public static final String PATTERN_FONT_COLOR = "\\[color=#([0-9A-Fa-f]{6})\\](([^(\\[/\\])]*))\\[/\\]";
	
	private int startIndex;
	
	private int endIndex;
	
	private Vector4f color;
	
	public RangeColor(int startIndex, int endIndex, Vector4f color) {
		this.startIndex = startIndex;
		this.endIndex = endIndex;
		this.color = color;
	}
	
	public boolean isRangeColor(int index) {
		return index >= startIndex && index <=endIndex;
	}

	public int getStartIndex() {
		return startIndex;
	}

	public int getEndIndex() {
		return endIndex;
	}

	public Vector4f getColor() {
		return color;
	}
	
	@Override
	public String toString() {
		return String.format("startIndex:%s, endIndex:%s, color:%s", 
				this.startIndex, this.endIndex, this.color.toString());
	}

	public static String resplice(String text) {
		Pattern pattern = Pattern.compile(PATTERN_FONT_COLOR);
		Matcher matcher = pattern.matcher(text);
		StringBuilder builder = new StringBuilder();
		int index = 0;
		while(matcher.find()) {
			builder.append(StringUtils.substring(text, index, matcher.start()));
			String content = matcher.group();
			String color = matcher.group(1);
			if(StringUtils.contains(content, "\n")) {
				builder.append(StringUtils.replace(content, "\n", StringUtils.join("[/]\n[color=#", color, "]")));
			} else {
				builder.append(content);
			}
			index = matcher.end();
		}
		if(index > 0) {
			builder.append(StringUtils.substring(text, index));
			return builder.toString();
		}
		return text;
	}
	
}
